import React from 'react';
import { createForm } from 'rc-form';
import { connect } from 'react-redux';

import {WingBlank, Card, Picker, List, InputItem, TextareaItem, Modal, Toast } from 'antd-mobile';

import MyModal from '../../common/Modal';
import Pick from '../../common/Picker';

import {withClient} from '../../../hoc';

import cities from '../../../utils/cityData';
import {getPickerData, getLabelValueData, getNotEmptyObj} from '../../../utils/crmUtils';

@withClient
@createForm()
@connect((state) => ({access_token: state.token.access_token}))
export default class CustomerBaseEdit extends React.Component{
    constructor(props) {
        super(props);
        this.state={
            customerInsuredNumberDatas: [],
            customerLevelDatas: [],
            customerStaffSizeDatas: [],
            allProduct: [],
            customerParameterSet: [],
            customerDemand: [],
            source: [],
            companyNum: [],
        }
    }

    getSourceParentId = () => {
        let id 
        this.state.source.map(item => {
            item.children.map(i => {
                if(Number(i.value) === Number(this.props.data.customerSource)){
                    id = item.value;
                }
            })
        } )
        return id;
    }

    getOptions = async () => {
        const [
            customerParameterSet,
            allProduct,
            customerDemand,
            source,
        ] = await Promise.all([
            this.props.client.post('/crm/api/mobile/customerParameterSet/getSet', { access_token: this.props.access_token }),
            this.props.client.post('/crm/api/mobile/product/getAllEnableProduct', { access_token: this.props.access_token }),
            this.props.client.post('/crm/api/mobile/customerDemand/getCustomerDemand', {access_token: this.props.access_token}),
            this.props.client.post('/crm/api/mobile/dictionary/getDataList', { access_token: this.props.access_token }),
        ]);
        let {customerInsuredNumberDatas, customerLevelDatas, customerStaffSizeDatas} = customerParameterSet.data;
        this.setState({
            customerInsuredNumberDatas: getLabelValueData(customerInsuredNumberDatas),
            customerLevelDatas: getLabelValueData(customerLevelDatas),
            customerStaffSizeDatas: getLabelValueData(customerStaffSizeDatas),
            allProduct: getLabelValueData(allProduct.data, 'name', 'id'),
            // customerParameterSet: getLabelValueData(customerParameterSet.data),
            customerDemand: getLabelValueData(customerDemand.data, 'demand', 'id'),
            source: getPickerData(source.data.souces, 'dictName', 'id', 'sons'),
            companyNum: getPickerData(source.data.companyNums, 'dictName', 'id', 'sons'),
            businessTypes: getPickerData(source.data.businessTypes, 'typeName', 'id', 'sons'),
        });
    }

    checkName = async() => {
        const cName = this.props.form.getFieldValue('cName');
        const res = await this.props.client.post('/crm/api/mobile/customer/checkCName',{cName, customerType: 3, access_token: this.props.access_token});
        if(Number(res.status) !== 0){
            Toast.fail(res.msg, 1);
        }else{
            if(res.data){
                Toast.fail(res.data.msg, 1);
            }
        }
    }

    save = () => {
        this.props.form.validateFields(async (err, values) => {
            if(!err){
                console.log(values);
                const p = cities.filter(item => Number(item.value) === Number(values.city[0]))[0];
                const c = p.children.filter(item => Number(item.value) === Number(values.city[1]))[0];
                values.province = values.city[0];
                values.provinceName = p.label;
                values.city = values.city[1];
                values.cityName = c.label;
                values.customerSource = values.customerSource[1];
                const res = await this.props.client.post('/crm/api/mobile/customer/update',
                {
                    ...getNotEmptyObj(values), 
                    access_token: this.props.access_token,
                    id: this.props.data.id,
                }
                );
                if(Number(res.status) === 0){
                    this.props.onSave();
                }
            }else{
                const msg = Object.values(err)[0].errors[0].message;
                Toast.fail(msg, 1);
            }
        })
    }

    componentDidMount() {
        if (__CLIENT__) {
            setTimeout(async () => {
                await this.getOptions();
            }, 0);
        }
    }

    render() {

        const { getFieldDecorator, getFieldValue } = this.props.form;

        const {
            customerInsuredNumberDatas,
            customerLevelDatas,
            customerStaffSizeDatas,
            allProduct,
            // customerParameterSet,
            customerDemand,
            source,
            companyNum,
            businessTypes,

            qxbVisible,
        } =this.state;

        const {data, isQxb} = this.props;
        const pId = this.getSourceParentId()

        // console.log(data.cooperationIntention && data.cooperationIntention.split(','));

        return (
            <MyModal
                visible={this.props.visible}
                title={'编辑客户基本信息'}
                leftContent='关闭'
                onCannel={() => { 
                    const alertInstance = Modal.alert('退出','当前页面还没有保存，是否确定关闭？', [
                        { text: '取消', onPress: () => alertInstance.close(), style: 'default' },
                        { text: '确定', onPress: () => this.props.onCannel() },
                    ]);
                }}
                rightContent={[<span key={'save'} onClick={this.save}>保存</span>]}
            >
                <div className='page-add-customer-content'>
                <WingBlank size='md'>
                    <List className='global-list'>

                        {getFieldDecorator('type', {
                            validateFirst: true,
                            initialValue: [data.type],
                            rules: [
                                {
                                validator: (rules, value, callback) => {
                                    if(!value){
                                        callback('请填写客户类型');
                                    }else{
                                        callback();
                                    }
                                }
                                }
                            ]
                        })(<Picker
                            key="客户类型"
                            extra="必填"
                            cols={1}
                            data={[{ label: '企业', value: 0 }, { label: '社会组织', value: 1 }, { label: '境外客户', value: 2 }]}
                            title="客户类型"
                            disabled={isQxb || data.customerStatus !== 0} 
                        >
                            <List.Item arrow="down">客户类型</List.Item>
                        </Picker>)}

                        {getFieldDecorator('cName', {
                            validateFirst: true,
                            initialValue: data.cName,
                            rules: [
                                {
                                validator: (rules, value, callback) => {
                                    if(!value){
                                        callback('请填写客户名称')
                                    }else if(value < 2){
                                        callback('客户名称不可少于2个字')
                                    }else{
                                        // this.checkName();
                                        callback();
                                    }
                                }
                                }
                            ]
                        })(<InputItem 
                            clear 
                            placeholder="必填" 
                            // onBlur={this.checkName}
                            // extra={isQxb ? '' : <i className='crmiconfont crmicon-qiyegongshangxinxi'/>}
                            // onExtraClick={this.openGong}
                            disabled={true}
                            >
                            客户名称
                        </InputItem>)}

                        {getFieldDecorator('city', {
                            validateFirst: true,
                            initialValue:[data.province, data.city],
                            rules: [
                                {
                                validator: (rules, value, callback) => {
                                    console.log(value);
                                    if(!value){
                                        callback('请填写客户所在地');
                                    }else{
                                        callback();
                                    }
                                }
                                }
                            ]
                        })(<Picker
                            key="客户所在地"
                            extra="必填"
                            cols={2}
                            data={cities}
                            title="客户所在地"
                            onOk={e => console.log('ok', e)}
                            onDismiss={e => console.log('dismiss', e)}
                            disabled={isQxb || data.customerStatus !== 0}
                        >
                            <List.Item arrow="down">客户所在地</List.Item>
                        </Picker>)}

                        {getFieldDecorator('address', {
                            initialValue: data.address,
                            rules: [
                                {
                                validator: (rules, value, callback) => {
                                    callback();
                                }
                                }
                            ]
                        })(<InputItem 
                            clear 
                            placeholder="请填写详细地址" 
                            disabled={isQxb || data.customerStatus !== 0}
                            >
                            {' '}
                        </InputItem>)}

                        {getFieldDecorator('customerSource', {
                            initialValue:[pId,data.customerSource],
                            validateFirst: true,
                            rules: [
                                {
                                validator: (rules, value, callback) => {
                                    if(!value){
                                        callback('请填写客户来源');
                                    }else{
                                        callback();
                                    }
                                }
                                }
                            ]
                        })(<Picker
                            key="客户来源"
                            extra="必填"
                            cols={2}
                            data={source}
                            title="客户来源"
                        >
                            <List.Item arrow="down">客户来源</List.Item>
                        </Picker>)}

                        {getFieldDecorator('customerParamLevel', {
                            initialValue: [data.customerParamLevel],
                            validateFirst: true,
                            rules: [
                                {
                                validator: (rules, value, callback) => {
                                    if(!value){
                                        callback('请填写客户等级');
                                    }else{
                                        callback();
                                    }
                                }
                                }
                            ]
                        })(<Picker
                            key="客户等级"
                            extra="必填"
                            cols={1}
                            data={customerLevelDatas}
                            title="客户等级"
                            onOk={e => console.log('ok', e)}
                            onDismiss={e => console.log('dismiss', e)}
                        >
                            <List.Item arrow="down">客户等级</List.Item>
                        </Picker>)}

                        {getFieldDecorator('customerStaffSize', {
                            initialValue: [data.customerStaffSize],
                            validateFirst: true,
                            rules: [
                                {
                                validator: (rules, value, callback) => {
                                    if(!value){
                                        callback('请填写公司规模');
                                    }else{
                                        callback();
                                    }
                                }
                                }
                            ]
                        })(<Picker
                            key="公司规模"
                            extra="必填"
                            cols={1}
                            data={customerStaffSizeDatas}
                            title="公司规模"
                            onOk={e => console.log('ok', e)}
                            onDismiss={e => console.log('dismiss', e)}
                        >
                            <List.Item arrow="down">公司规模</List.Item>
                        </Picker>)}

                        {getFieldDecorator('customerInsuredNumber', {
                            initialValue: [data.customerInsuredNumber],
                            validateFirst: true,
                            rules: [
                                {
                                validator: (rules, value, callback) => {
                                    if(!value){
                                        callback('请填写预计参保人数');
                                    }else{
                                        callback();
                                    }
                                }
                                }
                            ]
                        })(<Picker
                            key="预计参保人数"
                            extra="必填"
                            cols={1}
                            data={customerInsuredNumberDatas}
                            title="预计参保人数"
                            onOk={e => console.log('ok', e)}
                            onDismiss={e => console.log('dismiss', e)}
                        >
                            <List.Item arrow="down">预计参保人数</List.Item>
                        </Picker>)}

                        {getFieldDecorator('insureStatus', {
                            initialValue: data.insureStatus ? data.insureStatus.split(',').map(item => Number(item)) : undefined,
                            rules: [
                                {
                                validator: (rules, value, callback) => {
                                    callback();
                                }
                                }
                            ]
                        })(<Pick
                            key="员工参保情况"
                            data={[{ label: '自缴', value: 1 }, { label: '代缴', value: 2 }, { label: '未缴', value: 3 }, { label: '其他', value: 4}]}
                            title="员工参保情况"
                        >
                            员工参保情况
                        </Pick>)}

                        {getFieldDecorator('cooperationIntention', {
                            initialValue: data.cooperationIntention ? data.cooperationIntention.split(',').map(item => `${item}`) : undefined,
                            // initialValue: [45, 50],
                            validateFirst: true,
                            rules: [
                                {
                                validator: (rules, value, callback) => {
                                    if(!value || value[0] === undefined){
                                        callback('请填写合作意向');
                                    }else{
                                        callback();
                                    }
                                }
                                }
                            ]
                        })(<Pick
                            key="合作意向"
                            placeholder='必填'
                            data={allProduct}
                            title="合作意向"
                        >
                            合作意向
                        </Pick>)}

                        {getFieldDecorator('customerDemand', {
                            initialValue: data.customerDemand ? data.customerDemand.split(',').map(item => Number(item)) : undefined,
                            rules: [
                                {
                                validator: (rules, value, callback) => {
                                    callback();
                                }
                                }
                            ]
                        })(<Pick
                            key="客户需求"
                            data={customerDemand}
                            title="客户需求"
                        >
                            客户需求
                        </Pick>)}

                        {getFieldDecorator('remark', {
                            initialValue:data.remark,
                            rules: [
                                {
                                validator: (rules, value, callback) => {
                                    callback();
                                }
                                }
                            ]
                        })(<TextareaItem rows={5} count={100} placeholder="点击填写" title="备注" />)}

                    </List>
                </WingBlank>
                </div>
            </MyModal>
        );
    }
}
